import moment from 'moment';
import React from 'react';
import nzh from 'nzh/cn';
import {parse, stringify} from 'qs';
// import createHistory from 'history/createBrowserHistory';
import {createBrowserHistory} from 'history';
import 'moment/locale/zh-cn';

moment.locale('zh-cn');


export function formatPhone(phone) {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")
}

export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

export function getDate(amount = 1) {
  return moment().subtract(amount, 'days').format('YYYY-MM-DD');
}

export function getDateValue() {
  return moment();
}

export function getTimeDistance(type, now = new Date()) {
  const dayMap = {
    'today': 0,
    'yesterday': 1,
    '2days': 1,
    '7days': 6,
    '10days': 9,
    '30days': 29,
  };

  if (Object.keys(dayMap).includes(type)) {
    const prevTime = moment(now).subtract(dayMap[type], 'day').startOf('day');
    const nextTime = moment(now).endOf('day');
    return [prevTime, nextTime];
  } else {
    const oneDay = 1000 * 60 * 60 * 24;
    if (type === 'week') {
      let day = now.getDay();
      now.setHours(0);
      now.setMinutes(0);
      now.setSeconds(0);
      if (day === 0) {
        day = 6;
      } else {
        day -= 1;
      }
      const beginTime = now.getTime() - day * oneDay;
      return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
    } else if (type === 'month') {
      const year = now.getFullYear();
      const month = now.getMonth();
      const nextDate = moment(now).add(1, 'months');
      const nextYear = nextDate.year();
      const nextMonth = nextDate.month();

      return [
        moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
        moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
      ];
    }
    const year = now.getFullYear();
    return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
  }
}


export function getPlainNode(nodeList, parentPath = '') {
  const arr = [];
  nodeList.forEach(node => {
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

export function digitUppercase(n) {
  return nzh.toMoney(n);
}

function getRelation(str1, str2) {
  if (str1 === str2) {
    console.warn('Two path are equal!'); // eslint-disable-line
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
  }
  if (arr1.every((item, index) => item === arr2[index])) {
    return 2;
  }
  return 3;
}

function getRenderArr(routes) {
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
    // 去重
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
    // 是否包含
    const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path
  );
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
  const renderRoutes = renderArr.map(item => {
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
      exact,
      ...routerData[`${path}${item}`],
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}

export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

export function getQueryPath(path = '', query = {}) {
  const search = stringify(query);
  if (search.length) {
    return `${path}?${search}`;
  }
  return path;
}

/* eslint no-useless-escape:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export function isUrl(path) {
  return reg.test(path);
}

export function formatWan(val) {
  const v = val * 1;
  if (!v || Number.isNaN(v)) return '';

  let result = val;
  if (val > 10000) {
    result = Math.floor(val / 10000);
    result = (
      <span>
        {result}
        <span
          styles={{
            position: 'relative',
            top: -2,
            fontSize: 14,
            fontStyle: 'normal',
            lineHeight: 20,
            marginLeft: 2,
          }}
        >
          万
        </span>
      </span>
    );
  }
  return result;
}


export function ts2time(ts, exact) {
    if (exact === 'minute') {
        return moment(ts * 1e3).format('YY-MM-DD HH:mm');
    }
    return moment(ts * 1e3).format('YYYY-MM-DD HH:mm:ss');
}

export function ts2date(ts) {
  return moment(ts * 1e3).format('YYYY-MM-DD');
}

const unitMap = {
  years: ' 年 ',
  months: ' 月 ',
  days: ' 天 ',
  hours: ' 小时 ',
  minutes: ' 分钟 ',
  seconds: ' 秒 ',
};

export function test(a) {
  return a+'cy'
}
export function secs2time(mss) {
  const obj = {};
  obj.years = Math.floor(mss / (1000 * 60 * 60 * 24 * 30 * 12));
  obj.months = Math.floor(mss % (1000 * 60 * 60 * 24 * 30 * 12) / (1000 * 60 * 60 * 24 * 30));
  obj.days = Math.floor(mss % (1000 * 60 * 60 * 24 * 30) / (1000 * 60 * 60 * 24));
  obj.hours = Math.floor((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  obj.minutes = Math.floor((mss % (1000 * 60 * 60)) / (1000 * 60));
  obj.seconds = (mss % (1000 * 60)) / 1000;

  for (let i = 0, arr = Object.keys(unitMap), len = arr.length; i < len; i++) {
    if (obj[arr[i]]) {
        let result =  obj[arr[i]]+ unitMap[arr[i]]
        while(++i<len){
            result = obj[arr[i ]] + unitMap[arr[i ]]
        }
        return result
    }
  }
}

const WALK_HIGH_SPEED = 1.5;  // m/s, about 5.4kmpm
const BIKE_HIGH_SPEED = 10.0;  // about 20mph
const DRIVE_HIGH_SPEED = 30.0; // about 90mph

export function computeColor(speed) {
  if (speed === -1) {
    return '000000'
  }
  let r, g, b, ratio;
  if (speed <= WALK_HIGH_SPEED) {
    ratio = speed / WALK_HIGH_SPEED;
    r = Math.round(127 + 128 * ratio);
    g = 0;
    b = 0;
  } else if (speed <= BIKE_HIGH_SPEED) {
    ratio = (speed - WALK_HIGH_SPEED) / (BIKE_HIGH_SPEED - WALK_HIGH_SPEED);
    r = Math.round(255 * (1 - ratio));
    g = Math.round(255 * ratio);  // to be optimized
    b = 0;
  } else {
    if (speed > DRIVE_HIGH_SPEED) {
      speed = DRIVE_HIGH_SPEED;
    }
    ratio = (speed - BIKE_HIGH_SPEED) / (DRIVE_HIGH_SPEED - BIKE_HIGH_SPEED);
    r = 0;
    g = Math.round(255 * (1 - ratio));
    b = Math.round(255 * ratio);
  }
  return rgb2html(r, g, b);

}

function rgb2html(red, green, blue) {
  const decColor = blue + 256 * green + 65536 * red;
  let color;
  if (decColor < 256) {
    color = "0000" + decColor.toString(16);
  } else if (decColor < 65536) {
    color = "00" + decColor.toString(16);
  } else {
    color = "" + decColor.toString(16);
  }
  return '#' + color;
}


// export const history = createHistory();
export const history = createBrowserHistory();
